# Replication script for
#
# "Political Divisions in Large Cities:
# The Socio-Spatial Basis of Legislative Behavior in Chicago and Toronto"
# Journal of Politics
#
# ASSEMBLE FIGURES
#
# November 2, 2023
#
# Zack Taylor, University of Western Ontario, zack.taylor@uwo.ca
# David A. Armstrong II, University of Western Ontario, dave.armstrong@uwo.ca

library(tibble)
library(dplyr)  
library(purrr)
library(ggplot2)
library(tidyr)
library(stringr)
library(cowplot)
library(scales)
library(ggrepel)
library(ggridges)
library(ggpubr)

# SET UP CONSOLE LOG FILE ----

assemble_figures_log <- file("assemble_figures_log.txt")
sink(assemble_figures_log, append = TRUE, type = "output") # Writing console output to log file
sink(assemble_figures_log, append = TRUE, type = "message")
cat(readChar(rstudioapi::getSourceEditorContext()$path, # Writing currently opened R script to file
             file.info(rstudioapi::getSourceEditorContext()$path)$size))


load("temp/toronto_figures.rda")
load("temp/chicago_figures.rda")

figures <- NULL 

figures <- c(tor_figures, chi_figures)

dpi = 800


## Figure 1 (assembled) ----

scale = 1
ggarrange(figures[['fig1chi_apre']], 
          figures[['fig1tor_apre']],
          ncol = 2,
          labels = c("Chicago", "Toronto"),
          label.x = 0.1,
          font.label = list(size = 8, color = "black", face = "bold", family = NULL),
          common.legend = TRUE,
          legend = "bottom")
ggsave(plot = last_plot(),
       filename = paste0("tabsfigs/fg1_", seed, ".tiff"),
       width = 7,
       height = 3,
       scale = scale,
       units = "in",
       dpi = dpi,
       bg = "white",
       compression = "lzw")

## Figure 2 (assembled) ----

ggarrange(figures[['fig2chi_movement']], 
          figures[['fig2tor_movement']],
          ncol = 2,
          labels = c("Chicago", "Toronto"),
          label.x = 0,
          font.label = list(size = 8, color = "black", face = "bold", family = NULL)
          #common.legend = TRUE,
          #legend = "bottom"
)
ggsave(plot = last_plot(),
       filename = paste0("tabsfigs/fg2_", seed, ".tiff"),
       width = 7,
       height = 2,
       scale = scale,
       units = "in",
       dpi = dpi,
       bg = "white",
       compression = "lzw")


## Figure 3 ----

scale = 1.3
cowplot::plot_grid(figures[['fig3achi_cor_d1']] + theme(axis.text.x = element_blank(),
                                                        axis.ticks.x = element_blank(),
                                                        axis.title.x = element_blank(),
                                                        plot.margin = unit(c(0,0,.25,0), "in")), 
          figures[['fig3bchi_cor_d2']],
          align = "v",
          ncol = 1,
          labels = c("Dimension 1", "Dimension 2"),
          label_size = 10 * scale,
          label_colour = "black",
          label_fontface = "bold",
          label_x = 0,
          label_y = 1,
          vjust = .25,
          rel_heights = c(1, 1.3)
) + 
  theme(plot.margin = unit(c(0.25,0.1,0,0), "in")) 

ggsave(plot = last_plot(),
         filename = paste0("tabsfigs/fg3_", seed, ".tiff"),
         width = 7,
         height = 7,
         scale = scale,
         units = "in",
         dpi = dpi * scale,
         bg = "white",
         compression = "lzw")

## Figure 4 ----

scale = 1
ggsave(figures[['fig4chi_race']],
       filename = paste0("tabsfigs/fg4_", seed, ".tiff"),
       width = 7,
       height = 4,
       scale = scale,
       units = "in",
       dpi = dpi,
       compression = "lzw")

## Figure 5 ----

scale = 1.3
cowplot::plot_grid(figures[['fig5ator_cor_d1']] + theme(axis.text.x = element_blank(),
                                                        axis.ticks.x = element_blank(),
                                                        axis.title.x = element_blank(),
                                                        plot.margin = unit(c(0,0,.25,0), "in")), 
                   figures[['fig5btor_cor_d2']],
                   align = "v",
                   ncol = 1,
                   labels = c("Dimension 1", "Dimension 2"),
                   label_size = 10 * scale,
                   label_colour = "black",
                   label_fontface = "bold",
                   label_x = 0,
                   label_y = 1,
                   vjust = .25,
                   rel_heights = c(1, 1.4)
) + 
  theme(plot.margin = unit(c(0.25,0.1,0,0), "in")) 

ggsave(plot = last_plot(),
       filename = paste0("tabsfigs/fg5_", seed, ".tiff"),
       width = 7,
       height = 9,
       scale = scale,
       units = "in",
       dpi = dpi * scale,
       bg = "white",
       compression = "lzw")


## Figure A1 (assembled) ----

ggarrange(figures[['figA1chi_votes']], 
          figures[['figA1tor_votes']],
          ncol = 2)

scale = 1.3
ggsave(last_plot(),
       filename = paste0("tabsfigs/fgA1_", seed, ".png"),
       width = 6.5,
       height = 1.5,
       scale = scale,
       units = "in",
       dpi = dpi
)

## Figure A2 (assembled) ----

ggarrange(figures[['figA2chi_betas']], 
          figures[['figA2tor_betas']],
          ncol = 1)

scale = 1.75
ggsave(last_plot(),
       filename = paste0("tabsfigs/fgA2_", seed, ".png"),
       width = 6.5,
       height = 4,
       scale = scale,
       units = "in",
       dpi = dpi
)

## Table A2 - APRE comparison ----

load("temp/chi_apre.rda")
load("temp/tor_apre.rda")
load("temp/chi_nom_apre.rda")
load("temp/tor_nom_apre.rda")


chi_apre <- chi_apre %>% mutate(model = "legR") 
tor_apre <- tor_apre %>% mutate(model = "legR")


chi_apre_all <- chi_nom_apre %>% filter(session == "Overall") %>% 
  mutate(model = as.character(model)) %>% 
  select(model, apre) %>% 
  group_by(model) %>% 
  summarise(apre = sum(apre)) %>%
  bind_rows(chi_apre %>% 
              filter(session == "Overall") %>% 
              select(model, apre) %>% 
              group_by(model) %>% 
              summarise(apre=sum(apre))) %>% 
  mutate(city = "Chicago")

tor_apre_all <- tor_nom_apre %>% filter(session == "Overall") %>% 
  mutate(model = as.character(model)) %>% 
  select(model, apre) %>% 
  group_by(model) %>% 
  summarise(apre = sum(apre)) %>%
  bind_rows(tor_apre %>% 
              filter(session == "Overall") %>% 
              select(model, apre) %>% 
              group_by(model) %>% 
              summarise(apre=sum(apre))) %>% 
  mutate(city = "Toronto")


apre_comparison <- bind_rows(chi_apre_all, tor_apre_all)  %>%
  mutate(model = factor(model, 
                        levels=c("DW-NOMINATE", "legR", "W-NOMINATE (one-shot)", "W-NOMINATE (term-by-term)"))) 

figures[['tabA2apre_comparison']] <- ggplot(apre_comparison, 
                                            aes(x=as.factor(city), 
                                                y=as.factor(model), 
                                                fill = -apre)) + 
  geom_tile(show.legend = FALSE) + 
  geom_text(aes(label = round(apre, 2)), color="white") + 
  theme_classic() + 
  labs(x="City", y="Model")+ 
  coord_cartesian(expand=FALSE)

scale = 1
ggsave(plot = last_plot(),
       filename = paste0("tabsfigs/tbA2.png"),
       width = 6.5,
       height = 2,
       scale = scale,
       units = "in",
       dpi = dpi,
       bg = "white")

## Figure A3 Toronto (assembled) - DW-NOM correlations ----

scale = 1.4
cowplot::plot_grid(figures[['tor_cor_d1_dw']] + theme(axis.text.x = element_blank(),
                                                      axis.ticks.x = element_blank(),
                                                      axis.title.x = element_blank(),
                                                      plot.margin = unit(c(0,0,.25,0), "in")), 
                   figures[['tor_cor_d2_dw']],
                   align = "v",
                   ncol = 1,
                   labels = c("Dimension 1", "Dimension 2"),
                   label_size = 10 * scale,
                   label_colour = "black",
                   label_fontface = "bold",
                   label_x = 0,
                   label_y = 1,
                   vjust = .25,
                   rel_heights = c(0.9, 1)
) + 
  theme(plot.margin = unit(c(0.25,0.1,0,0), "in")) 

ggsave(plot = last_plot(),
       filename = paste0("tabsfigs/fgA3_tor_dw.png"),
       width = 6.5,
       height = 9,
       scale = scale,
       units = "in",
       dpi = dpi,
       bg = "white")

## Figure A4 Chicago (assembled) - DW-NOM correlations ----

scale = 1.4
cowplot::plot_grid(figures[['chi_cor_d1_dw']] + theme(axis.text.x = element_blank(),
                                                      axis.ticks.x = element_blank(),
                                                      axis.title.x = element_blank(),
                                                      plot.margin = unit(c(0,0,.25,0), "in")), 
                   figures[['chi_cor_d2_dw']],
                   align = "v",
                   ncol = 1,
                   labels = c("Dimension 1", "Dimension 2"),
                   label_size = 10 * scale,
                   label_colour = "black",
                   label_fontface = "bold",
                   label_x = 0,
                   label_y = 1,
                   vjust = .25,
                   rel_heights = c(length(unique(figures[["chi_cor_d1_dw"]][["data"]][['fac']])), 
                                   length(unique(figures[["chi_cor_d2_dw"]][["data"]][['fac']])))
) + 
  theme(plot.margin = unit(c(0.25,0.1,0,0), "in")) 

ggsave(plot = last_plot(),
       filename = paste0("tabsfigs/fgA4_chi_dw.png"),
       width = 6.5,
       height = 5,
       scale = scale,
       units = "in",
       dpi = dpi,
       bg = "white")

## Figure A5 DW-NOM Correlations Toronto (Curated Data, two 1D Models) ----

scale = 1.4
cowplot::plot_grid(figures[['tor_cor_d1_dwc1']]  + theme(axis.text.x = element_blank(),
                                                         axis.ticks.x = element_blank(),
                                                         axis.title.x = element_blank(),
                                                         plot.margin = unit(c(0,0,.25,0), "in")), 
                   figures[['tor_cor_d2_dwc1']],
                   align = "v",
                   ncol = 1,
                   labels = c("Dimension 1", "Dimension 2"),
                   label_size = 10 * scale,
                   label_colour = "black",
                   label_fontface = "bold",
                   label_x = 0,
                   label_y = 1,
                   vjust = .25,
                   rel_heights = c(0.51, .49)
) + 
  theme(plot.margin = unit(c(0.25,0.1,0,0), "in")) 

ggsave(plot = last_plot(),
       filename = "tabsfigs/fgA5_tor.tiff",
       width = 7,
       height = 8,
       scale = scale,
       units = "in",
       dpi = dpi,
       bg = "white",
       compression = "lzw")

## Figure A6 DW-NOM Correlations Toronto (Curated Data, one 2D Model) ----

scale = 1.4
cowplot::plot_grid(figures[['tor_cor_d1_dwca']]  + theme(axis.text.x = element_blank(),
                                                         axis.ticks.x = element_blank(),
                                                         axis.title.x = element_blank(),
                                                         plot.margin = unit(c(0,0,.25,0), "in")), 
                   figures[['tor_cor_d2_dwca']],
                   align = "v",
                   ncol = 1,
                   labels = c("Dimension 1", "Dimension 2"),
                   label_size = 10 * scale,
                   label_colour = "black",
                   label_fontface = "bold",
                   label_x = 0,
                   label_y = 1,
                   vjust = .25,
                   rel_heights = c(0.45, .55)
) + 
  theme(plot.margin = unit(c(0.25,0.1,0,0), "in")) 

ggsave(plot = last_plot(),
       filename = "tabsfigs/fgA6_tor.tiff",
       width = 7,
       height = 8,
       scale = scale,
       units = "in",
       dpi = dpi,
       bg = "white",
       compression = "lzw")


## Figure A7 DW-NOM Correlations Chicago (Curated Data, one 2D Model) ----

scale = 1.4
cowplot::plot_grid(figures[['chi_cor_d1_dwca']]  + theme(axis.text.x = element_blank(),
                                                         axis.ticks.x = element_blank(),
                                                         axis.title.x = element_blank(),
                                                         plot.margin = unit(c(0,0,.25,0), "in")), 
                   figures[['chi_cor_d2_dwca']],
                   align = "v",
                   ncol = 1,
                   labels = c("Dimension 1", "Dimension 2"),
                   label_size = 10 * scale,
                   label_colour = "black",
                   label_fontface = "bold",
                   label_x = 0,
                   label_y = 1,
                   vjust = .25,
                   rel_heights = c(0.45, .55)
) + 
  theme(plot.margin = unit(c(0.25,0.1,0,0), "in")) 

ggsave(plot = last_plot(),
       filename = "tabsfigs/fgA7_chi.tiff",
       width = 7,
       height = 8,
       scale = scale,
       units = "in",
       dpi = dpi,
       bg = "white",
       compression = "lzw")

# ## Figure A5 Toronto (assembled) - W-NOM correlations ----
# 
# scale = 1.4
# cowplot::plot_grid(figures[['tor_cor_d1_wn']] + theme(axis.text.x = element_blank(),
#                                                       axis.ticks.x = element_blank(),
#                                                       axis.title.x = element_blank(),
#                                                       plot.margin = unit(c(0,0,.25,0), "in")), 
#                    figures[['tor_cor_d2_wn']],
#                    align = "v",
#                    ncol = 1,
#                    labels = c("Dimension 1", "Dimension 2"),
#                    label_size = 10 * scale,
#                    label_colour = "black",
#                    label_fontface = "bold",
#                    label_x = 0,
#                    label_y = 1,
#                    vjust = .25,
#                    rel_heights = c(.65, 1)
# ) + 
#   theme(plot.margin = unit(c(0.25,0.1,0,0), "in")) 
# 
# ggsave(plot = last_plot(),
#        filename = paste0("tabsfigs/fgA5_tor_wn.png"),
#        width = 6.5,
#        height = 7.5,
#        scale = scale,
#        units = "in",
#        dpi = dpi,
#        bg = "white")
# 
# ## Figure A6 Chicago (assembled) - W-NOM correlations ----
# 
# scale = 1.4
# cowplot::plot_grid(figures[['chi_cor_d1_wn']] + theme(axis.text.x = element_blank(),
#                                                       axis.ticks.x = element_blank(),
#                                                       axis.title.x = element_blank(),
#                                                       plot.margin = unit(c(0,0,.25,0), "in")), 
#                    figures[['chi_cor_d2_wn']],
#                    align = "v",
#                    ncol = 1,
#                    labels = c("Dimension 1", "Dimension 2"),
#                    label_size = 10 * scale,
#                    label_colour = "black",
#                    label_fontface = "bold",
#                    label_x = 0,
#                    label_y = 1,
#                    vjust = 0,
#                    rel_heights = c(.9, 1)
# ) + 
#   theme(plot.margin = unit(c(0.25,0.1,0,0), "in")) 
# 
# ggsave(plot = last_plot(),
#        filename = paste0("tabsfigs/fgA6_chi_wn.png"),
#        width = 6.5,
#        height = 3,
#        scale = scale,
#        units = "in",
#        dpi = dpi,
#        bg = "white")
# 
# ## Figure A7 Toronto (assembled) - W-NOM 1-shot correlations ----
# 
# scale = 1.4
# cowplot::plot_grid(figures[['tor_cor_d1_w1']] + theme(axis.text.x = element_blank(),
#                                                       axis.ticks.x = element_blank(),
#                                                       axis.title.x = element_blank(),
#                                                       plot.margin = unit(c(0,0,.25,0), "in")), 
#                    figures[['tor_cor_d2_w1']],
#                    align = "v",
#                    ncol = 1,
#                    labels = c("Dimension 1", "Dimension 2"),
#                    label_size = 10 * scale,
#                    label_colour = "black",
#                    label_fontface = "bold",
#                    label_x = 0,
#                    label_y = 1,
#                    vjust = .25,
#                    rel_heights = c(0.9, 1)
# ) + 
#   theme(plot.margin = unit(c(0.25,0.1,0,0), "in")) 
# 
# ggsave(plot = last_plot(),
#        filename = paste0("tabsfigs/fgA7_tor_w1.png"),
#        width = 6.5,
#        height = 8,
#        scale = scale,
#        units = "in",
#        dpi = dpi,
#        bg = "white")
# 
# ## Figure A8 Chicago (assembled) - W-NOM 1-shot correlations ----
# 
# scale = 1.4
# cowplot::plot_grid(figures[["chi_cor_d1_w1"]] + theme(axis.text.x = element_blank(),
#                                                       axis.ticks.x = element_blank(),
#                                                       axis.title.x = element_blank(),
#                                                       plot.margin = unit(c(0,0,.25,0), "in")), 
#                    figures[["chi_cor_d2_w1"]],
#                    align = "v",
#                    ncol = 1,
#                    labels = c("Dimension 1", "Dimension 2"),
#                    label_size = 10 * scale,
#                    label_colour = "black",
#                    label_fontface = "bold",
#                    label_x = 0,
#                    label_y = 1,
#                    vjust = .25,
#                    rel_heights = c(0.9, 1)
# ) + 
#   theme(plot.margin = unit(c(0.25,0.1,0,0), "in")) 
# 
# ggsave(plot = last_plot(),
#        filename = paste0("tabsfigs/fgA8_chi_w1.png"),
#        width = 6.5,
#        height = 9,
#        scale = scale,
#        units = "in",
#        dpi = dpi,
#        bg = "white")


## Figure C1 (assembled) ----

ggarrange(figures[['figC1chi_unanimity']], 
          figures[['figC1tor_unanimity']],
          ncol = 1,
          widths = c(1.5, 1)
)

scale = 1
ggsave(last_plot(),
       filename = paste0("tabsfigs/fgC1_", seed, ".png"),
       width = 6.5,
       height = 7.5,
       scale = scale,
       units = "in",
       dpi = dpi
)

## Figure D1 ----

scale = 1.3
ggsave(figures[['figD1chi_moran']],
       filename = paste0("tabsfigs/fgD1.png"),
       width = 6.5,
       height = 6,
       scale = scale,
       units = "in",
       dpi = dpi)

## Figure D2 ----

scale = 1.3
ggsave(figures[['figD2tor_moran']],
       filename = paste0("tabsfigs/fgD2.png"),
       width = 6.5,
       height = 6,
       scale = scale,
       units = "in",
       dpi = dpi)

## Figure E1 ----

ggarrange(figures[['figE1chi_r1']],
          figures[['figE1chi_r2']],
          ncol = 2
)

scale = 1
ggsave(last_plot(),
       filename = paste0("tabsfigs/fgE1chi_", seed, ".png"),
       width = 6.5,
       height = 7.5,
       scale = scale,
       units = "in",
       dpi = dpi
)

## Figure E2 ----

ggarrange(figures[['figE2tor_r1']],
          figures[['figE2tor_r2']],
          ncol = 2
)

scale = 1
ggsave(last_plot(),
       filename = paste0("tabsfigs/fgE2tor_", seed, ".png"),
       width = 6.5,
       height = 7.5,
       scale = scale,
       units = "in",
       dpi = dpi
)

closeAllConnections() # Close connection to log file
